package org.tio.examples.httpImpl.server;

import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

import org.tio.core.Aio;
import org.tio.core.ChannelContext;
import org.tio.core.GroupContext;
import org.tio.core.exception.AioDecodeException;
import org.tio.examples.httpImpl.common.HttpPacket;
import org.tio.server.intf.ServerAioHandler;

public class HttpAioHandler implements ServerAioHandler<Object, HttpPacket, Object>{
    
    @Override
    public Object handler(HttpPacket packet, ChannelContext<Object, HttpPacket, Object> channelContext)
            throws Exception {
        StringBuffer sb = new StringBuffer();  
        sb.append("GET /mypage/button.html HTTP/1.1\r\n");  
        sb.append("Host:localhost\r\n");  
        sb.append("Accept-Language:zh-cn\r\n");  
        sb.append("Connection:Keep-Alive\r\n");  
        //请求头结束  
        sb.append("\r\n");
        sb.append("dsfasdfasdfa");
        packet.setBody(sb.toString().getBytes());
        Aio.send(channelContext, packet);
        return null;
    }
    
    @Override
    public HttpPacket decode(ByteBuffer buffer, ChannelContext channelContext) throws AioDecodeException {
        byte[] bs = buffer.array();
        HttpPacket hp = new HttpPacket();
        try {
            hp.setBody(bs);
            String s1 = new String(bs,"utf-8");
            System.out.println(s1);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return hp;
    }

    @Override
    public ByteBuffer encode(HttpPacket packet, GroupContext<Object, HttpPacket, Object> groupContext,
            ChannelContext<Object, HttpPacket, Object> channelContext) {
        byte[] b = packet.getBody();
        ByteBuffer bb = ByteBuffer.allocate(b.length);
        bb.put(b);
        return bb;
    }

}
